
package com.jefe;

import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.auth.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.xml.sax.InputSource;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.*;
/**
 *
 * @author Sonali Mendis
 * Hudson Portlet for Jefe (http://www.jefesolutions.com)
 * GNU License
 */
public class Driver {

    private ArrayList<HudsonProject> project;
    private String error = null;
    private String host = null;
    private int port = 0;
    private String fil = null;
    private String user = null;
    private String pass = null;

    public Driver(){
        project = new ArrayList<HudsonProject>();
    }
    public ArrayList<HudsonProject> setProject(String hostApp, int portApp, String filter, String currentUser, String currentPass){
        try{
            this.fil = filter;
            this.host = hostApp;
            this.port = portApp;
            this.user = currentUser;
            this.pass = currentPass;
            InputStream in = null;

            HttpClient client = new HttpClient();

                    client.getState().setCredentials(
                            new AuthScope( host, port, "realm"),
                            new UsernamePasswordCredentials( user, pass)
                            );
                    client.getParams().setAuthenticationPreemptive(true);
                    GetMethod get = new GetMethod("http://"+host+":"+port+"/hudson/api/xml");
                    get.setDoAuthentication(true);
                     try{
                         int status = client.executeMethod(get);
                         in = get.getResponseBodyAsStream();
                         if(in!=null){
                            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                            Document doc = dBuilder.parse(new InputSource(in));
                            doc.getDocumentElement().normalize();

                            NodeList nList = doc.getElementsByTagName("job");
                            Boolean found = false;

                            for (int temp = 0; temp < nList.getLength(); temp++) {
                                Node nNode = nList.item(temp);
                                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                                    HudsonProject pro = new HudsonProject();
                                    Element eElement = (Element) nNode;
                                    
                                    String key = getTagValue("name", eElement);
                                    String searchFrom = key.toUpperCase();
                                    String toSearch = fil.toUpperCase();
                                    
                                    if(fil.equals("*")){
                                        found = true;
                                        pro.setProjectName(key);
                                        pro.setProjectURL(getTagValue("url",eElement));
                                        pro.setBuildStatusFromColor(getTagValue("color",eElement));
                                        project.add(pro);
                                    }else{

                                        int searchFromLength = searchFrom.length();
                                        int toSearchLength = toSearch.length();
                                        for (int i = 0; i <= (searchFromLength - toSearchLength); i++) {
                                            if (searchFrom.regionMatches(i, toSearch, 0, toSearchLength)) {
                                                found = true;
                                                pro.setProjectName(getTagValue("name",eElement));
                                                pro.setProjectURL(getTagValue("url",eElement));
                                                pro.setBuildStatusFromColor(getTagValue("color",eElement));
                                                project.add(pro);
                                            }
                                        }
                                    }
                                }
                            }
                            if(!found){
                                        error = "This user either doesn't have access to this project or this project doesn't exist.";
                            }
                         }else{
                             System.out.println("Input Stream is null...\n");
                         }
                     }finally{
                         get.releaseConnection();
                     }

        }catch(UnknownHostException ex){
            error = "The Remote host can not be detected.";
        }catch(Exception e){
            error = e.getMessage();
        }
        return project;
    }
    private static String getTagValue(String sTag, Element eElement)
     {
	  NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
	  Node nValue = (Node) nlList.item(0);

	  return nValue.getNodeValue();
     }
     public String getErrors(){
        if(error==null){
            if(project.size()==0){
                error = "No projects for the user \""+user+"\" in this repository.";
            }
        }
        return error;
    }
}
